﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;

namespace Wicresoft.NRemedy.VS10Addin.UI
{
    public class Parser
    {
        public List<string> GetIsMappedSchema(string xmlContent)
        {
            if(string.IsNullOrEmpty(xmlContent)) 
                return new List<string>();
            rmcg config = XmlDeserialize<rmcg>(xmlContent);
            List<string> returns = new List<string>();
            if (config.Mappings == null)
                return returns;
            foreach (var map in config.Mappings)
            {
                if (map.EntityTypeMapping != null 
                    && !string.IsNullOrEmpty(map.EntityTypeMapping.TypeName))
                {
                    if (map.EntityTypeMapping.MappingFragment != null
                        && !string.IsNullOrEmpty(map.EntityTypeMapping.MappingFragment.StoreEntitySet))
                    {
                        returns.Add(map.EntityTypeMapping.TypeName);
                    }
 
                }
 
            }

            return returns;
 
        }

        public static string CreateRMCGFile(rmcg rmcg)
        {
            return XmlSerializer<rmcg>(rmcg);
 
        }

        public static rmcg CreateRMCGObject(string xml)
        {
            return XmlDeserialize<rmcg>(xml);
        }

        private static string XmlSerializer<T>(T serialObject) where T : class
        {
            XmlSerializer ser = new XmlSerializer(typeof(T));
            System.IO.MemoryStream mem = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(mem, Encoding.Unicode);
            writer.Formatting = Formatting.Indented;
            ser.Serialize(writer, serialObject);
            writer.Close();

            return Encoding.Unicode.GetString(mem.ToArray());
        }

        private static T XmlDeserialize<T>(string str) where T : class
        {
            XmlSerializer mySerializer = new XmlSerializer(typeof(T));
            StreamReader mem2 = new StreamReader(
                    new MemoryStream(System.Text.Encoding.Unicode.GetBytes(str)),
                    System.Text.Encoding.Unicode);

            return (T)mySerializer.Deserialize(mem2);
        }
    }
}
